import React, { useState } from 'react';
import {
  Typography,
  Card,
  Form,
  Select,
  Button,
  Space,
  Alert,
  Steps,
  Radio,
  Input,
  Checkbox,
  Table,
  Tag,
  Progress
} from 'antd';
import {
  CloudUploadOutlined,
  SafetyCertificateOutlined,
  CheckCircleOutlined,
  LoadingOutlined,
  ExclamationCircleOutlined
} from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;
const { Option } = Select;

interface DeployTarget {
  id: string;
  type: 'cdn' | 'lb' | 'oss' | 'k8s';
  name: string;
  provider: string;
  region: string;
  status: 'deployed' | 'deploying' | 'failed' | 'pending';
}

interface Certificate {
  id: string;
  domain: string;
  provider: string;
  status: 'valid' | 'expired';
}

const CertificateDeploy: React.FC = () => {
  const [form] = Form.useForm();
  const [currentStep, setCurrentStep] = useState(0);
  const [selectedCertificate, setSelectedCertificate] = useState<string>();
  const [selectedTargets, setSelectedTargets] = useState<string[]>([]);
  const [deploying, setDeploying] = useState(false);
  const [deployResults, setDeployResults] = useState<DeployTarget[]>([]);

  // 模拟证书数据
  const certificates: Certificate[] = [
    { id: '1', domain: 'example.com', provider: "Let's Encrypt", status: 'valid' },
    { id: '2', domain: '*.demo.com', provider: 'ZeroSSL', status: 'valid' },
    { id: '3', domain: 'api.example.com', provider: '阿里云SSL', status: 'valid' },
  ];

  // 模拟部署目标
  const deployTargets: DeployTarget[] = [
    {
      id: '1',
      type: 'cdn',
      name: 'CDN-Production',
      provider: '阿里云',
      region: '华东1',
      status: 'pending'
    },
    {
      id: '2',
      type: 'lb',
      name: 'LoadBalancer-Web',
      provider: '腾讯云',
      region: '华南1',
      status: 'pending'
    },
    {
      id: '3',
      type: 'oss',
      name: 'OSS-Static',
      provider: '阿里云',
      region: '华东2',
      status: 'pending'
    },
    {
      id: '4',
      type: 'k8s',
      name: 'K8S-Cluster',
      provider: 'AWS',
      region: 'us-east-1',
      status: 'pending'
    },
  ];

  const getTypeIcon = (type: DeployTarget['type']) => {
    const icons = {
      cdn: '🌐',
      lb: '⚖️',
      oss: '📦',
      k8s: '🐳'
    };
    return icons[type];
  };

  const getTypeName = (type: DeployTarget['type']) => {
    const names = {
      cdn: 'CDN',
      lb: '负载均衡',
      oss: '对象存储',
      k8s: 'K8S集群'
    };
    return names[type];
  };

  const getStatusConfig = (status: DeployTarget['status']) => {
    const configs = {
      deployed: { color: 'success', text: '已部署', icon: <CheckCircleOutlined /> },
      deploying: { color: 'processing', text: '部署中', icon: <LoadingOutlined /> },
      failed: { color: 'error', text: '部署失败', icon: <ExclamationCircleOutlined /> },
      pending: { color: 'default', text: '待部署', icon: null }
    };
    return configs[status];
  };

  const steps = [
    {
      title: '选择证书',
      description: '选择要部署的SSL证书',
    },
    {
      title: '选择目标',
      description: '选择部署目标服务',
    },
    {
      title: '配置参数',
      description: '配置部署参数',
    },
    {
      title: '开始部署',
      description: '执行部署并查看结果',
    },
  ];

  const handleNext = async () => {
    try {
      await form.validateFields();
      setCurrentStep(currentStep + 1);
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handlePrev = () => {
    setCurrentStep(currentStep - 1);
  };

  const handleDeploy = async () => {
    setDeploying(true);
    setCurrentStep(3);

    // 模拟部署过程
    const selectedTargetObjects = deployTargets.filter(target => 
      selectedTargets.includes(target.id)
    );

    setDeployResults(selectedTargetObjects.map(target => ({
      ...target,
      status: 'deploying'
    })));

    // 模拟逐个部署
    for (let i = 0; i < selectedTargetObjects.length; i++) {
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      setDeployResults(prev => prev.map((target, index) => {
        if (index === i) {
          return {
            ...target,
            status: Math.random() > 0.1 ? 'deployed' : 'failed' // 90%成功率
          };
        }
        return target;
      }));
    }

    setDeploying(false);
  };

  const renderStepContent = () => {
    switch (currentStep) {
      case 0:
        return (
          <Card>
            <Form.Item
              name="certificate"
              label="选择证书"
              rules={[{ required: true, message: '请选择证书' }]}
            >
              <Radio.Group 
                value={selectedCertificate}
                onChange={(e) => setSelectedCertificate(e.target.value)}
              >
                <Space direction="vertical" style={{ width: '100%' }}>
                  {certificates.map(cert => (
                    <Radio key={cert.id} value={cert.id}>
                      <Space>
                        <SafetyCertificateOutlined style={{ color: '#52c41a' }} />
                        <Text strong>{cert.domain}</Text>
                        <Text type="secondary">({cert.provider})</Text>
                        <Tag color="success">有效</Tag>
                      </Space>
                    </Radio>
                  ))}
                </Space>
              </Radio.Group>
            </Form.Item>

            <Alert
              message="选择要部署的证书"
              description="只显示状态为有效的证书，确保证书未过期且可以正常使用"
              type="info"
              showIcon
              style={{ marginTop: 16 }}
            />
          </Card>
        );

      case 1:
        return (
          <Card>
            <Form.Item
              name="targets"
              label="部署目标"
              rules={[{ required: true, message: '请选择至少一个部署目标' }]}
            >
              <Checkbox.Group 
                value={selectedTargets}
                onChange={setSelectedTargets}
                style={{ width: '100%' }}
              >
                <Space direction="vertical" style={{ width: '100%' }} size="middle">
                  {deployTargets.map(target => (
                    <Card key={target.id} size="small" style={{ width: '100%' }}>
                      <Checkbox value={target.id}>
                        <Space>
                          <span style={{ fontSize: 16 }}>{getTypeIcon(target.type)}</span>
                          <div>
                            <Text strong>{target.name}</Text>
                            <br />
                            <Text type="secondary" style={{ fontSize: 12 }}>
                              {getTypeName(target.type)} - {target.provider} ({target.region})
                            </Text>
                          </div>
                        </Space>
                      </Checkbox>
                    </Card>
                  ))}
                </Space>
              </Checkbox.Group>
            </Form.Item>

            <Alert
              message="选择部署目标"
              description="可以同时部署到多个目标，部署过程将按顺序进行"
              type="info"
              showIcon
              style={{ marginTop: 16 }}
            />
          </Card>
        );

      case 2:
        return (
          <Card>
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <Form.Item
                name="autoUpdate"
                label="自动更新"
                valuePropName="checked"
              >
                <Checkbox>启用证书自动更新（推荐）</Checkbox>
              </Form.Item>

              <Form.Item
                name="backupOld"
                label="备份旧证书"
                valuePropName="checked"
              >
                <Checkbox>部署前备份现有证书</Checkbox>
              </Form.Item>

              <Form.Item
                name="healthCheck"
                label="健康检查"
                valuePropName="checked"
              >
                <Checkbox>部署后进行SSL健康检查</Checkbox>
              </Form.Item>

              <Form.Item
                name="rollbackOnFailure"
                label="失败回滚"
                valuePropName="checked"
              >
                <Checkbox>部署失败时自动回滚</Checkbox>
              </Form.Item>

              <Form.Item
                name="notificationEmail"
                label="通知邮箱"
              >
                <Input placeholder="部署完成后发送通知邮件" />
              </Form.Item>
            </Space>

            <Alert
              message="配置部署参数"
              description="建议启用自动更新和健康检查以确保证书部署的可靠性"
              type="warning"
              showIcon
              style={{ marginTop: 16 }}
            />
          </Card>
        );

      case 3:
        const completedCount = deployResults.filter(r => r.status === 'deployed').length;
        const failedCount = deployResults.filter(r => r.status === 'failed').length;
        const deployingCount = deployResults.filter(r => r.status === 'deploying').length;
        const totalProgress = deployResults.length > 0 ? 
          ((completedCount + failedCount) / deployResults.length) * 100 : 0;

        const columns: ColumnsType<DeployTarget> = [
          {
            title: '目标',
            key: 'target',
            render: (_, record) => (
              <Space>
                <span style={{ fontSize: 16 }}>{getTypeIcon(record.type)}</span>
                <div>
                  <Text strong>{record.name}</Text>
                  <br />
                  <Text type="secondary" style={{ fontSize: 12 }}>
                    {getTypeName(record.type)} - {record.provider}
                  </Text>
                </div>
              </Space>
            ),
          },
          {
            title: '区域',
            dataIndex: 'region',
            key: 'region',
          },
          {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: DeployTarget['status']) => {
              const config = getStatusConfig(status);
              return (
                <Space>
                  {config.icon}
                  <Tag color={config.color}>{config.text}</Tag>
                </Space>
              );
            },
          },
        ];

        return (
          <Card>
            <Space direction="vertical" style={{ width: '100%' }} size="large">
              <div>
                <Title level={4}>部署进度</Title>
                <Progress 
                  percent={Math.round(totalProgress)} 
                  status={deploying ? 'active' : 'normal'}
                  format={(percent) => `${completedCount}/${deployResults.length} 完成`}
                />
              </div>

              <Table
                columns={columns}
                dataSource={deployResults}
                rowKey="id"
                pagination={false}
                size="small"
              />

              {!deploying && deployResults.length > 0 && (
                <Alert
                  message={`部署完成！成功: ${completedCount}, 失败: ${failedCount}`}
                  type={failedCount > 0 ? 'warning' : 'success'}
                  showIcon
                />
              )}
            </Space>
          </Card>
        );

      default:
        return null;
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: '32px' }}>
        <Title level={2} style={{ margin: 0, marginBottom: '8px' }}>
          <CloudUploadOutlined style={{ marginRight: '8px', color: '#1890ff' }} />
          证书部署
        </Title>
        <Text type="secondary">
          将SSL证书部署到CDN、负载均衡、对象存储等云服务
        </Text>
      </div>

      <div style={{ maxWidth: 800, margin: '0 auto' }}>
        <Card style={{ marginBottom: '24px' }}>
          <Steps
            current={currentStep}
            items={steps}
            style={{ marginBottom: '32px' }}
          />

          <Form
            form={form}
            layout="vertical"
            initialValues={{
              autoUpdate: true,
              backupOld: true,
              healthCheck: true,
              rollbackOnFailure: true,
            }}
          >
            {renderStepContent()}
          </Form>

          <div style={{ 
            display: 'flex', 
            justifyContent: 'space-between', 
            marginTop: '32px',
            paddingTop: '24px',
            borderTop: '1px solid #f0f0f0'
          }}>
            <Button
              onClick={handlePrev}
              disabled={currentStep === 0}
            >
              上一步
            </Button>

            <div>
              {currentStep < steps.length - 2 && (
                <Button type="primary" onClick={handleNext}>
                  下一步
                </Button>
              )}
              {currentStep === steps.length - 2 && (
                <Button
                  type="primary"
                  onClick={handleDeploy}
                  icon={<CloudUploadOutlined />}
                  disabled={selectedTargets.length === 0}
                >
                  开始部署
                </Button>
              )}
              {currentStep === steps.length - 1 && (
                <Space>
                  <Button onClick={() => {
                    setCurrentStep(0);
                    setSelectedCertificate(undefined);
                    setSelectedTargets([]);
                    setDeployResults([]);
                    form.resetFields();
                  }}>
                    重新部署
                  </Button>
                </Space>
              )}
            </div>
          </div>
        </Card>
      </div>
    </div>
  );
};

export default CertificateDeploy; 